package com.yupi.yuapiinterface.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yupi.yuapiinterface.model.User;
import com.yupi.yuapiinterface.utils.SignUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.Map;

//调用第三方接口的API

public class YuApiClient {

    private String accessKey;
    private String secretKey;

    public YuApiClient() {}

    public YuApiClient(String accessKey, String secretKey) {
        this.secretKey = secretKey;
        this.accessKey = accessKey;
    }

    public String getNameByGet(String name) {
        // 可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result= HttpUtil.get("http://localhost:8123/api/name/", paramMap);
        System.out.println(result);
        return result;
    }

    public String getNameByPost(@RequestParam String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result= HttpUtil.post("http://localhost:8123/api/name/", paramMap);
        System.out.println(result);
        return result;
    }


    public String getUserNameByPost(@RequestBody User user) {
        //将User对象转为json字符串
        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post("http://localhost:8123/api/name/user")
                .addHeaders(getHeaderMap(json))
                .body(json)
                .execute(); //执行请求
        System.out.println("打印服务器返回的状态码: " + httpResponse.getStatus());
        String result = httpResponse.body();
        System.out.println("获取服务器返回的结果" + result);
        return result;
    }

    // 创建一个私有方法，用于构造请求头
    private Map<String, String> getHeaderMap(String body) {
        Map<String, String> hashMap = new HashMap<>();
        // 将 "accessKey" 和 "secretKey" 添加到请求头中
        hashMap.put("accessKey", accessKey);
        //注意：不能直接发送秘钥
        // hashMap.put("secretKey", secretKey);
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        hashMap.put("body", body);   //请求体内容
        hashMap.put("timestamp", String.valueOf(System.currentTimeMillis()/1000)); //随机数，防止重放
        hashMap.put("sign", SignUtils.genSign(body, secretKey));

        // 返回构造的请求头
        return hashMap;
    }

}
